﻿
#
# Author : itech
# 

import logging

# ====================================================
# Common logger

class NullHandler(logging.Handler):
  def emit(self, record): pass

class GlobalLogging:

  log = None

  @staticmethod
  def getInstance():
    if GlobalLogging.log == None: 
      GlobalLogging.log = GlobalLogging()
    return GlobalLogging.log
  

  def __init__(self):
    self.logger = None
    self.handler = None
    self.level = logging.INFO
    self.logger = logging.getLogger("GlobalLogging")
    self.formatter = logging.Formatter("%(levelname)s - %(message)s")
    nh = NullHandler()
    self.logger.addHandler(nh)
      
  def setLoggingToFile(self,file): 
      fh = logging.FileHandler(file)
      fh.setFormatter(self.formatter)
      self.logger.addHandler(fh)
      
  def setLoggingToConsole(self) : 
      ch = logging.StreamHandler()
      ch.setFormatter(self.formatter)
      self.logger.addHandler(ch)
      
  # custom the way to handle log
  def setLoggingToHanlder(self,handler): 
      self.handler = handler
      
  def setLoggingLevel(self,level):
    self.level = level
    self.logger.setLevel(level)
    
  def debug(self,s):
      self.logger.debug(s)
      if not self.handler == None and self.level <= logging.DEBUG :
        tp = 'Debug'
        self.handler(tp, tp + ':' + s)
  def info(self,s):
      self.logger.info(s)
      if not self.handler == None and self.level <= logging.INFO:
        tp = 'Info'
        self.handler(tp, tp + ':' + s)
  def warning(self,s):
      self.logger.warn(s)
      if not self.handler == None and self.level <= logging.WARNING:
        tp = 'Warning'
        self.handler(tp, tp + ':' + s)
  def error(self,s):
      self.logger.error(s)
      if not self.handler == None and self.level <= logging.ERROR:
        tp = 'Error'
        self.handler(tp, tp + ':' + s)
  def critical(self,s):
      self.logger.critical(s)
      if not self.handler == None and self.level <= logging.CRITICAL:
        tp = 'Critical'
        self.handler(tp, tp + ':' + s)


